package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"logprocess/pkg/setting"
)

var db *gorm.DB

type Model struct{}

// Setup initializes the database instance
func Setup() {
	db = setup(setting.DbSetting)

	// 统计表
	if !db.AutoMigrate().HasTable(&AccessLogSummary{}) {
		db.AutoMigrate(&AccessLogSummary{})
	}
}

func setup(dbSetting *setting.Database) (_db *gorm.DB) {
	var err error
	_db, err = gorm.Open(dbSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		dbSetting.User,
		dbSetting.Password,
		dbSetting.Host,
		dbSetting.Name))

	if err != nil {
		log.Fatalf("models.Setup err: %v", err)
	}

	_db.LogMode(true)

	// 设置默认表名的命名规则
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return setting.DbSetting.TablePrefix + defaultTableName
	}
	// 禁用默认表名的负数形式
	_db.SingularTable(true)
	_db.DB().SetMaxIdleConns(10)
	_db.DB().SetMaxOpenConns(100)
	return
}
